package com.kosmos.dubhe.wxcp.provider;

import com.kosmos.dubhe.wxcp.config.WxCpConfiguration;
import com.kosmos.dubhe.wxcp.setting.WxcpUserScannerSetting;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.NoSuchElementException;


/**
 * @author wukai
 */
@Component
@Data
@Slf4j
public class WxCpUserProvider {
    List<WxCpUser> userList;
    private final WxcpUserScannerSetting setting;

    @PostConstruct
    public void init() {
        syncUser();
    }

    public WxCpUser getUserByName(String name) {
        return userList.stream().filter(u -> name.equals(u.getName())).findFirst().get();
    }

    public String getUserCode(String userName) {
        try {
            return getUserByName(userName).getUserId();
        } catch (NoSuchElementException e) {
            String message = String.format("WxCpUserProvider getUserCode to query userName:[%s] , user not exist , ", userName);
            log.error(message);
            throw new NoSuchElementException(message);
        }
    }

    public void syncUser() {
        try {
            userList = WxCpConfiguration.getCpService(setting.getAgentId())
                    .getUserService()
                    .listSimpleByDepartment(setting.getRootDepartmentId(), true, WxCpUserStatus.ENABLE.value);
        } catch (WxErrorException e) {
            log.error("UserProvider syncUser occur exception ", e);
        }
    }

}
